package com.gmp.rooms.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gmp.common.annotation.Log;
import com.gmp.common.core.controller.BaseController;
import com.gmp.common.core.domain.AjaxResult;
import com.gmp.common.enums.BusinessType;
import com.gmp.rooms.domain.Facilities;
import com.gmp.rooms.service.IFacilitiesService;
import com.gmp.common.utils.poi.ExcelUtil;
import com.gmp.common.core.page.TableDataInfo;

/**
 * 设施管理Controller
 *
 * @author Koi
 * @date 2025-07-28
 */
@RestController
@RequestMapping("/rooms/Facilities")
@Api(tags = "设施管理")
public class FacilitiesController extends BaseController {
    @Autowired
    private IFacilitiesService facilitiesService;

    /**
     * 查询设施管理列表
     */
    @PreAuthorize("@ss.hasPermi('rooms:Facilities:listAll')")
    @GetMapping("/list")
    @ApiOperation("查询设施管理列表")
    public TableDataInfo list(Facilities facilities) {
        startPage();
        List<Facilities> list = facilitiesService.selectFacilitiesList(facilities);
        return getDataTable(list);
    }

    /**
     * 根据厂房编号查询设施管理列表
     */
    @PreAuthorize("@ss.hasPermi('rooms:Facilities:list')")
    @PostMapping("/listByRoomCode/{roomCode}")  // 改为POST方法，路径参数roomCode保留
    @ApiOperation("根据厂房编号查询设施管理列表")
    public TableDataInfo listByRoomCode(@RequestBody Facilities facilities, @PathVariable String roomCode) {
        startPage();
        LambdaQueryWrapper<Facilities> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Facilities::getLocationRoomCode, roomCode);
        // 如果需要支持其他查询条件，可以从facilities对象中获取并添加到查询条件中
        // 例如：queryWrapper.like(Facilities::getFacilityName, facilities.getFacilityName());
        List<Facilities> list = facilitiesService.list(queryWrapper);
        return getDataTable(list);
    }


    /**
     * 导出设施管理列表
     */
    @PreAuthorize("@ss.hasPermi('rooms:Facilities:export')")
    @Log(title = "设施管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Facilities facilities) {
        List<Facilities> list = facilitiesService.selectFacilitiesList(facilities);
        ExcelUtil<Facilities> util = new ExcelUtil<Facilities>(Facilities.class);
        util.exportExcel(response, list, "设施管理数据");
    }

    /**
     * 获取设施管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('rooms:Facilities:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(facilitiesService.selectFacilitiesById(id));
    }


    /**
     * 根据 厂房room_code 新增设施管理
     */
    @PreAuthorize("@ss.hasPermi('rooms:Facilities:add')")
    @Log(title = "设施管理", businessType = BusinessType.INSERT)
    @ApiOperation("新增设施")
    @PostMapping("/newFacilities/{roomCode}")
    public AjaxResult add(@RequestBody Facilities facilities, @PathVariable String roomCode) {
        //设置逻辑删除
        facilities.setIsDelete(0);
        //设置room_code
        facilities.setLocationRoomCode(roomCode);
        //设置时间
        facilities.setCreatedAt(new Date());

        //生成设备编号
        // 规则：S + 厂房编号(去除R) + 4位随机数
        // 示例：roomCode=R20250728538 → 设施编号=S202507285386729
        // 1. 从roomCode中提取核心部分（去掉前缀R）
        String roomCodeCore = roomCode.replace("R", "");
        // 2. 生成4位随机数（0000-9999），确保同一厂房下编号唯一性
        String random = String.format("%04d", new Random().nextInt(10000));
        // 3. 拼接生成设施编号：S + 厂房核心编码 + 随机数
        String facilityCode = "S" + roomCodeCore + random;
        facilities.setFacilityCode(facilityCode);

        return toAjax(facilitiesService.save(facilities));
    }

    /**
     * 修改设施管理
     */
    @PreAuthorize("@ss.hasPermi('rooms:Facilities:edit')")
    @Log(title = "设施管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Facilities facilities) {
        return toAjax(facilitiesService.updateFacilities(facilities));
    }

    /**
     * 删除设施管理
     */
    @PreAuthorize("@ss.hasPermi('rooms:Facilities:remove')")
    @Log(title = "设施管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(facilitiesService.removeBatchByIds(Arrays.asList(ids)));
    }

    /**
     * 查询所以设施数据
     */
    @PreAuthorize("@ss.hasPermi('rooms:Facilities:findAll')")
    @PostMapping("/FindAll")
    @ApiOperation("查询所有设施")
    public AjaxResult FindAll(){
        return success(facilitiesService.selectFacilitiesList( null));
    }

    //根据location_room_code 查询对应所有设备信息
    @PreAuthorize("@ss.hasPermi('rooms:Facilities:findByRoomCode')")
    @PostMapping("/findByRoomCode/{roomCode}")
    @ApiOperation("根据location_room_code 查询对应所有设备信息")
    public AjaxResult findByRoomCode(@PathVariable String roomCode){
        LambdaQueryWrapper<Facilities> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Facilities::getLocationRoomCode, roomCode);
        return success(facilitiesService.list(queryWrapper));
    }


}
